package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Random;

import model.Account;

public class ServerProc extends Thread {

	private Socket client;
	private Server server;
	private Account account;
	private ObjectOutputStream objToClient;
	private DataOutputStream toClient;
	private DataInputStream fromClient;

	public ServerProc(Server server, Socket client) {
		this.server = server;
		this.client = client;

		System.out.println(client);
	}

	@Override
	public void run() {
		try {
			objToClient = new ObjectOutputStream(client.getOutputStream());
			fromClient = new DataInputStream(client.getInputStream());
			toClient = new DataOutputStream(client.getOutputStream());


			toClient.writeUTF("Welcome you to server");
			boolean connected = true;
			while (connected) {
				doCommand(fromClient, toClient, fromClient.readUTF());
			}
		} catch (Exception e) {
			try {
				this.join();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	private void doCommand(DataInputStream fromClient,
			DataOutputStream toClient, String command) {
		try {
			String username;
			switch (command) {
			case "GET-TOKEN":
				username = fromClient.readUTF();
				int pin = fromClient.readInt();
				if (check(username, pin)) {
					int token;
					toClient.writeInt(token = generateToken(username, pin));
					server.getDateTime();
					String oneTimePass = server.oneTimePass(account, token);
					account.setOneTimePassword(oneTimePass);
					server.updateAccount(account);
				} else {
					toClient.writeInt(-1);
				}
				break;
			case "LOGIN":
				username = fromClient.readUTF();
				String tokenPass = fromClient.readUTF();
				if (check(username)) {
					if (server.checkOneTimePass(username, tokenPass)) {
						objToClient.writeObject(server.getUser(username));
					}else{
						objToClient.writeObject(null);
					}
				}else{
					objToClient.writeObject(null);
				}
				break;
			}
		} catch (Exception e) {
		}
	}

	private boolean check(String username, int pin) {
		return (account = server.getAccount(username, pin)) != null;
	}

	private boolean check(String username) {
		return (account = server.getAccount(username)) != null;
	}

	private Random rd = new Random();

	private int generateToken(String username, int pin) {
		String code = rd.nextInt(999999) + "";
		while (code.length() < 6) {
			code += 0;
		}
		return Integer.parseInt(code);
	}

}
